#include "widget.h"
#include "./ui_widget.h"
#include <QString>
#include "crc.h"
#include <QRegularExpression>
#include <QMessageBox>
#include <QFile>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("盐氯机M款配置工具");
    QList<QString> cfg;
    cfg.append("F1");
    cfg.append("F2");
    cfg.append("F3");
    cfg.append("F4");
    cfg.append("10g");
    cfg.append("16g");
    cfg.append("22g");
    cfg.append("28g");
    ui->cb_cfg->addItems(cfg);
    QRegularExpression hex_8("^[0-9A-Fa-f]{8}$");
    QRegularExpressionValidator *hex_8_validator = new QRegularExpressionValidator(hex_8,ui->le_id);
    ui->le_id->setValidator(hex_8_validator);
}

Widget::~Widget()
{
    delete ui;
}

uint16_t Widget::generate_password(uint32_t id,uint8_t type)
{
    uint8_t buf[10] = {0};
    uint32_t _id = id;
    memcpy(buf,&_id,4);
    memset(&buf[4],type,4);
    return crc::crc16(buf,8);
}

void Widget::on_pb_generate_clicked()
{
    bool isOk;
    QString sid = ui->le_id->text();
    if(sid.length() != 8)
    {
        QMessageBox::warning(this,"提示","id需满足8个字符");
        return;
    }
    m_id = sid.toUInt(&isOk,16);
    if(isOk)
    {
        qDebug()<<QString::number(m_id,16);
    }
    else
    {
        return;
    }
    int cfgIndex = ui->cb_cfg->currentIndex();
    uint8_t cfgValue = (cfgIndex+1)|((cfgIndex+1)<<4);
    m_password = generate_password(m_id,cfgValue);
    ui->le_password->setText(QString("%1").arg(m_password,4,16,QChar('0')).toUpper());
}


void Widget::on_pb_generate_all_clicked()
{
    bool isOk;
    QList<QString> cfg;
    QString sid = ui->le_id->text();
    QFile f("password.txt");

    if(sid.length() != 8)
    {
        QMessageBox::warning(this,"提示","id需满足8个字符");
        return;
    }
    m_id = sid.toUInt(&isOk,16);
    if(isOk)
    {
        qDebug()<<QString::number(m_id,16);
    }
    else
    {
        return;
    }

    cfg.append("F1");
    cfg.append("F2");
    cfg.append("F3");
    cfg.append("F4");
    cfg.append("10g");
    cfg.append("16g");
    cfg.append("22g");
    cfg.append("28g");
    if(!f.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QMessageBox::warning(this,"提示","文件打开失败");
        return;
    }
    QTextStream out(&f);
    out<<"ID:"<<QString("%1").arg(m_id,8,16,QChar('0')).toUpper()<<'\n';
    for(int i=0;i<cfg.length();++i)
    {
        m_password = generate_password(m_id,0x11*(i+1));
        QString strPassword = QString("%1").arg(m_password,4,16,QChar('0')).toUpper();
        cfg[i].append(":").append(strPassword);
        out<<cfg.at(i)<<'\n';
    }
    f.close();
    qDebug()<<cfg;

}

